package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 实现spring security接口UserDetailsService实现
 */
@Component
public class SpringSecurityUserService implements UserDetailsService {

    // 使用dubbo通过网络远程调用服务提供方获取数据库中的用户信息
    @Reference
    private UserService userService;

    // 根据用户名查询数据库获取用户信息,此方法由spring security框架调用
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findByUsername(username);
        if (user == null){
            // 用户名不存在
            return null;
        }
        // 用户权限集合
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();

        // 动态为用户授权
        Set<Role> roles = user.getRoles();
        if (roles != null){
            for (Role role : roles) {
                // 遍历角色，为用户授予角色
                authorities.add(new SimpleGrantedAuthority(role.getKeyword()));
                // 授予角色
                Set<Permission> permissions = role.getPermissions();
                if (permissions != null){
                    for (Permission permission : permissions) {
                        // 遍历权限集合，为用户授权
                        authorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
                    }
                }
            }
        }
        // 用户名、密码、权限
        return new org.springframework.security.core.userdetails.User(username,user.getPassword(),authorities);
    }
}
